<?php

namespace app\api\controller\v1\common;

use app\Request;
use think\facade\App;
use think\Image;

class UploadController
{
    public function file(Request $request)
    {
        $file = $request->file('file');

        validate(['file' => [
            'fileSize' => 500 * 1024 * 1024,
            'fileExt'  => 'png,jpg,jpeg,gif,xls,xlsx,mp4'
        ]])->check(['file' => $file]) ;

        $saveName = \think\facade\Filesystem::disk('public')->putFile( 'upload', $file);


        $uploadUrl = $request->domain() .'/upload/' . $saveName ;

        return app('json')->success([
            'url' => $uploadUrl ,
        ]);
    }
    public function base64(Request $request)
    {
        $param  = $request->post('base64'  , '');
        if ($param) {
            header('Content-type:text/html;charset=utf-8');
            $base64_image_content = $param;
            //将base64编码转换为图片保存
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
                $img = md5(uniqid(microtime(true),true)).'.jpg';

                $file_path = date('Ymd').'/';
                $path= 'upload/'.$file_path;
                if(!file_exists($path)){
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($path,0777,true);
                }
                $new_file = $path . $img;
                //将图片保存到指定的位置
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                    return app('json')->success([
                        'url' => $request->domain() .'/'. $new_file ,
                    ]);

                }else{
                    return app('json')->fail('上传失败2');
                }
            }else{
                return app('json')->fail('上传失败');

            }

        }
    }
}